package com.yoooya.base.config;

import com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor;
import com.yoooya.base.dao.DalMapper;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan(basePackages = "com.yoooya.base.dao", annotationClass = DalMapper.class)
public class MyBatisConfig {

    @Autowired
    private ResourcePatternResolver resourcePatternResolver;
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean() throws Exception {
        Properties configurationProperties = new Properties();
        configurationProperties.setProperty("lazyLoadingEnabled", Boolean.TRUE.toString());
        configurationProperties.setProperty("multipleResultSetsEnabled", Boolean.TRUE.toString());
        configurationProperties.setProperty("safeRowBoundsEnabled", Boolean.TRUE.toString());
        configurationProperties.setProperty("mapUnderscoreToCamelCase", Boolean.TRUE.toString());
        configurationProperties.setProperty("lazyLoadTriggerMethods", "equals,clone,hashCode,toString");

        OffsetLimitInterceptor paginationInterceptor = new OffsetLimitInterceptor();
        paginationInterceptor.setDialectClass("com.github.miemiedev.mybatis.paginator.dialect.MySQLDialect");


        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.yoooya.base.model.po");
        bean.setMapperLocations(resourcePatternResolver.getResources("classpath*:dal/entities/**/*.xml"));
        bean.setConfigurationProperties(configurationProperties);
        bean.setPlugins(new Interceptor[] { paginationInterceptor });
        return bean;
    }

}
